How to use <> to assert typecast In HTML

In this approach, we will assert the type by specifying it inside the angular brackets (<>) just before the document selection of the element.

Syntax:

const var_name = <HTMLType> document.getElementById(ID');

Example: The below example will explain how you can assert HTMLElement using the angular brackets syntax.

Javascript




const appDiv =
    <HTMLDivElement>document.
        getElementById('app');
appDiv.innerHTML =
    `<h1>
    ${typeof appDiv}
</h1>`;


HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Page Title</title>
</head>
 
<body>
    <h2>Welcome To GFG</h2>
    <div id="app"></div>
</body>
 
</html>


Output:

Object

How to Assert a Type of an HTMLElement in TypeScript ?

In this article, we are going to learn the different ways of asserting the type of an HTMLElement in TypeScript. The type assertion is used to type the simple variables to JavaScript objects by defining the HTML element name.

There are many ways of performing this task as listed below:

Table of Content

  • Typing using the colon syntax
  • Using <> to assert typecast
  • Using item() method with asserting type
  • Using the any type with asserting type

Similar Reads

Typing using the colon syntax

This is the general way of typing the variables in TypeScript that can also be used to assert the HTMLElement as well in TypeScript....

Using <> to assert typecast

...

Using item() method with asserting type

...

Using the any type with asserting type

In this approach, we will assert the type by specifying it inside the angular brackets (<>) just before the document selection of the element....